package com.example.springbooteasycode.utils.excel;

import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFPalette;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;

import java.io.FileOutputStream;
import java.io.IOException;

public class ExcelExample {
    public static void main(String[] args) throws IOException {
        // 创建一个新的工作簿和表
        Workbook workbook = new HSSFWorkbook();
        Sheet sheet = workbook.createSheet("Sheet1");

        // 设置第 i 列的宽度
        int columnWidth = 20 * 256;
        for (int i = 0; i < 10; i++) {
            sheet.setColumnWidth(i, columnWidth);
        }

        // 创建一行并设置行高为 20 磅
        Row row = sheet.createRow(0);
        row.setHeightInPoints(20);

        // 创建单元格并写入一些数据
        Cell cell = row.createCell(0);
        cell.setCellValue("Hello, World!");

        // 创建单元格样式
        HSSFCellStyle cellStyle = (HSSFCellStyle) workbook.createCellStyle();

        // 获取调色板
        HSSFPalette palette = ((HSSFWorkbook) workbook).getCustomPalette();

        // 自定义颜色 (RGB)
        byte r = (byte) 255;
        byte g = (byte) 20;
        byte b = (byte) 147;
        HSSFColor customColor = palette.findSimilarColor(r, g, b); // 查找或创建相似颜色

        // 根据列索引设置不同的颜色
        if (0 < 6) {
            cellStyle.setFillForegroundColor(customColor.getIndex());
        } else {
            byte ry = (byte) 255;
            byte gy = (byte) 255;
            byte by = (byte) 0;
            HSSFColor customYellowColor = palette.findSimilarColor(ry, gy, by);
            cellStyle.setFillForegroundColor(customYellowColor.getIndex());
        }
        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);

        // 应用样式到单元格
        cell.setCellStyle(cellStyle);

        // 将工作簿写入文件
        try (FileOutputStream fileOut = new FileOutputStream("/Users/boykchen/Desktop/example.xls")) {
            workbook.write(fileOut);
        }

        // 关闭工作簿
        workbook.close();
    }
}
